<template>
	<view class="wrapper">
    <view class="pay-btn" @click="goPay">确定下单</view>
    <view class="products">
      <view class="item" v-for="(item, index) in productList" :key="index">
        <view class="image">
          <image :src="baseUrl + item.sku.image.thumbnail_path" v-if="item.sku && item.sku.image"></image>
          <image :src="baseUrl + item.mainImage.thumbnail_path" v-else-if="item.mainImage"></image>
        </view>
        <view class="desc">
          <view class="title two-lines">{{ item.title }}</view>
          <view class="sku" v-if="item.selected_sku_text">规格: {{ item.selected_sku_text | showText }}</view>
          <!--<view class="price">单价: ￥{{ (item.sku ? item.sku.price : item.price) * 1 }}, 数量: {{ item.quantity }}</view>-->
          <view class="price">单价: ￥{{ item.real_price ? item.real_price * 1 : item.price * 1 }}, 数量: {{ item.quantity }}</view>
          <!--<view class="total">总计: ￥{{ item.quantity * (item.sku ? item.sku.price : item.price) }}</view>-->
          <view class="total">总计: ￥{{ item.real_price ? item.quantity * item.real_price : item.quantity * item.price }}</view>
        </view>
      </view>
    </view>
    <view class="address">
      <view class="title">配送至:</view>
      <view class="list">
        <template v-for="(item, index) in addressList">
          <view class="item" v-if="index < 1 || !hiddenAddress"  :key="index">
            <view class="selected">
              <u-checkbox-group @change="selectAddress(item)">
                <u-checkbox :checked="item.selected" :activeColor="activeColor" iconSize="16px" size="20px" shape="circle" label=" " labelSize="0"></u-checkbox>
              </u-checkbox-group>
            </view>
            <!-- 小程序不支持这种写法 -->
            <!--<view class="desc" v-html="addressText(item)"></view>-->
            <view class="desc">
              <view class="line"><text class="left">收件人姓名: </text><text class="right">{{item.nickname}}</text></view>
              <view class="line"><text class="left">收件人电话: </text><text class="right color">{{item.mobile}}</text></view>
              <view class="line"><text class="left">地址: </text><text class="right" v-if="item.city">{{ item.city.province }}, {{ item.city.city }}, {{ item.city.area }}</text></view>
              <view class="line"><text class="left">详细地址: </text><text class="right info">{{item.address}}</text></view>
            </view>
          </view>
        </template>
      </view>
      <view class="ops" v-if="!hiddenAddress">
        <view class="add">
          <u-button :color="activeColor" type="primary" size="small" text="添加新地址" @click="goAddressAdd"></u-button>
        </view>
        <view class="all">
          <u-button type="primary" size="small" text="我的地址列表" @click="goAddressList"></u-button>
        </view>
      </view>
      <view class="more" @click="hiddenAddress = !hiddenAddress">
        <u-icon name="arrow-down" :color="activeColor" size="48" v-if="hiddenAddress"></u-icon>
        <u-icon name="arrow-up" :color="activeColor" size="48" v-else></u-icon>
      </view>
    </view>
    <view class="calc">
      <view class="title">总金额</view>
      <view class="item">
        <view class="text">商品总价:</view>
        <view class="num">￥{{ calcTotal.price * 1 }}</view>
      </view>
      <view class="item">
        <view class="text">总运费:</view>
        <view class="num" v-if="calcTotal.freight > 0">￥{{ calcTotal.freight * 1 }}</view>
        <view class="num" v-else>免运费</view>
      </view>
    </view>
    <view class="account">
      <view class="title">帐户总额:</view>
      <view class="item">
        <view class="text">余额:</view>
        <view class="num">{{ account.balance * 1 }}</view>
      </view>
    </view>
    <view class="amount">
      <view class="title">需要支付:</view>
      <view class="pay">{{ amount * 1 }}</view>
    </view>
    <view class="remark">
      <view class="title">备注:</view>
      <u--textarea v-model="remark" placeholder="请填写备注" autoHeight></u--textarea>
    </view>
    <!-- 支付密码 -->
    <u-modal :show="showPassword" :title="'支付密码'" showCancelButton @cancel="showPassword=false" @confirm="checkPassword">
      <view class="slot-content">
        <u--input
            v-model="password"
            type="password"
            border="surround"
            fontSize="24rpx"
            :customStyle="{'height': '30rpx'}"
            focus
        ></u--input>
      </view>
    </u-modal>
  </view>
</template>

<script>
import color from '@/config/color.js'
  // import { mapGetters } from 'vuex'
  import config from '../../config/config'
  import base64 from '../../util/base64'
  import Order from '../../api/order'
  const orderModel = new Order()
  const userModel = new User()

import { goApp } from '../../util/platform'
import User from '../../api/user'

	export default {
    computed: {
      // ...mapGetters({
      //   params: 'Order/params'
      // })
      // 计算总金额与运费
      calcTotal() {
        const total = {
          freight: 0,
          price: 0,
        }
        const list = [...this.productList]
        let freight = 0
        let price = 0
        list.forEach(x => {
          freight += x.quantity * x.freight
          if (this.isRemoteCity) {
            freight += x.quantity * x.remote_freight
          }
          if (x.sku) {
            price += x.quantity * x.sku.price
          } else {
            price += x.quantity * x.price
          }
        })
        total.freight = freight.toFixed(2)
        total.price = price.toFixed(2)
        return total
      },
      // 需要支付的现金
      amount() {
        const total = +this.calcTotal.price + +this.calcTotal.freight
        const use = +this.account.balance
        let amount = total - use
        if (amount < 0) {
          amount = 0
        }
        return (amount * 1).toFixed(2)
      }
    },
    filters: {
      showText(v) {
        return v.join(', ')
      },
      cityText(address) {
        let text
        text = `<view class="line"><text class="left">收件人姓名:</text><text class="right">${address.nickname}</text></view>`
        text += `<view class="line"><text class="left">收件电话:</text><text class="right color">${address.mobile}</text></view>`
        text += `<view class="line"><text class="left">地址:</text>
            <text class="right">${address.city.province}, ${address.city.city}, ${address.city.area}</text></view>`
        text += `<view class="line"><text class="left">详细地址:</text>
            <text class="right info">${address.address}</text></view>`
        return text
      }
    },
		data() {
			return {
        activeColor: color.main_color,
			  baseUrl: config.baseUrl,
			  params: {},
        productList: [],
        addressList: [],
        isRemoteCity: false,
        account: {},
        remark: '',
        hiddenAddress: true,
        showPassword: false,
        password: ''
			}
		},
		onLoad(options) {
      // console.log(options)
      /*
        参数处理, 判断是购物车,还是立即购买
       */
      const params = options.params
      if (params) {
        this.params = base64.parseUrl(params)
        // if (this.params.selected_sku_text) {
        //   this.params.selected_sku_text = base64.encode(this.params.selected_sku_text)
        // }
        // if (this.params.selected_sku_text && Array.isArray(this.params.selected_sku_text)) {
        //   this.params.selected_sku_text = this.params.selected_sku_text.map(x => encodeURIComponent(x))
        // }
        // if (this.params.selected_sku_text) {
        //   this.params.selected_sku_text = base64.parse(this.params.selected_sku_text)
        // }
        // console.log(this.params)
        this.uniRequest()
      } else {
        uni.showToast({
          title: '错误操作',
          icon: 'none',
          duration: 1000
        })
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/index/index'
          })
        }, 300)
      }
		},
    onUnload() {
      // 处理后退
      this.params = {}
      this.$store.dispatch('Order/set_params', {})
    },
    onShow() {
      // debug
      // this.params = {}
      // console.log(this.params)
      // 后退处理
      if (this.params && this.params.ok) {
        if (this.params.product_id) {
          uni.reLaunch({
            url: `/sub_product/detail/index?id=${this.params.product_id}`
          })
        } else {
          uni.switchTab({
            url: '/pages/cart/index'
          })
        }
      }
      // 地址重新加载
      this.getAddress()
      this.hiddenAddress = true
    },
		methods: {
      // 地址处理
      addressText(item) {
        return this.$options.filters.cityText(item)
      },
      goAddressAdd() {
        uni.navigateTo({
          url: '/sub_service/address/edit?type=-2'
        })
      },
      goAddressList() {
        uni.navigateTo({
          url: '/sub_service/address/index'
        })
      },
      selectAddress(item) {
        this.addressList.forEach(x => {
          if (x.id === item.id) {
            this.$set(x, 'selected', !x.selected)
            this._isRemoteCity(x.province_id)
          } else {
            this.$set(x, 'selected', false)
          }
        })
      },
      // 统一请求
      uniRequest() {
        this.getProduct()
        this.getAddress()
        this.getAccount()
      },
      getProduct() {
        orderModel.getProduct({ ...this.params }).then(response => {
          let { data } = response
          data = base64.parse(data)
          // this.productList = data.list
          // console.log(data.list)
          // 购物车与立即购买产品转换
          if (!this.params.cart) {
            if (data.list.selected_sku_text) {
              // data.list.selected_sku_text = base64.parse(decodeURI(data.list.selected_sku_text))
              // 这是最终解决方案, 在APP中, 中文乱码问题
              // 用加密是解决不了的
              data.list.selected_sku_text = this.$store.getters['Order/params'].selected_sku_text
              // console.log(data.list.selected_sku_text)
            }
            // if (data.list.selected_sku_text && Array.isArray(data.list.selected_sku_text)) {
            //   data.list.selected_sku_text = data.list.selected_sku_text.map(x => decodeURIComponent(x))
            // }
            this.productList = [data.list]
            console.log(this.productList)
          } else {
            data.list.forEach(item => {
              const obj = item.product
              obj.sku = item.sku || null
              obj.quantity = item.quantity
              if (item.selected_sku_text) {
                obj.selected_sku_text = item.selected_sku_text
              }
              this.productList.push(obj)
            })
          }
          console.log(this.productList)
        })
      },
      getAddress() {
        orderModel.getAddress().then(response => {
          let { data } = response
          data = base64.parse(data)
          this.addressList = data
          // console.log(data)
          this.addressList.forEach((v, k) => {
            if (k === 0) {
              this.$set(v, 'selected', true)
              this._isRemoteCity(v.province_id)
            } else {
              this.$set(v, 'selected', false)
            }
          })
        })
      },
      _isRemoteCity(province_id) {
        orderModel.isRemoteCity({ province_id }).then(response => {
          let { data } = response
          data = base64.parse(data)
          // console.log(data)
          this.isRemoteCity = data.result
        })
      },
      getAccount() {
        orderModel.getAccount().then(response => {
          let { data } = response
          data = base64.parse(data)
          this.account = data
        })
      },

      // 验证支付密码
      checkPassword() {
        userModel.verifyPayPassword({ password: this.password }).then(response => {
          this.password = ''
          this.showPassword = false
          const { data } = response
          const is = data.result
          if (!is) {
            uni.showToast({
              icon: 'none',
              title: '支付密码错误'
            })
          } else {
            this._goPay()
          }
        })
      },

      // 下单
      async goPay() {
        if (this.addressList.length === 0) {
          uni.showToast({
            title: '请添加收货地址',
            icon: 'none'
          })
          setTimeout(() => {
            uni.navigateTo({
              url: '/sub_service/address/edit?type=-2'
            })
          }, 500)
          return
        }
        // console.log(this.account.balance, this.amount)
        if (+this.amount > 0) {
          // return uni.showModal({
          //   title: '余额不足'
          // })
        }



        // 支付密码
        if (+this.amount === 0) {
          console.log('需要支付密码')
          const response = await userModel.checkPayPassword()
          let { data } = response
          data = base64.parse(data)
          const is = data.result
          if (!is) {
            uni.showToast({
              icon: 'none',
              title: '您还没有设置支付密码,现在去设置'
            })
            setTimeout(() => {
              uni.navigateTo({
                url: '/sub_service/pay-password/index'
              })
            }, 800)
          } else {
            // uni.showModal({
            //   title: '请输入支付密码',
            //   editable: true,
            //   success: res => {
            //     if (res.confirm) {
            //       const password = res.content
            //       userModel.verifyPayPassword({ password }).then(response => {
            //         const { data } = response
            //         const is = data.result
            //         if (!is) {
            //           uni.showToast({
            //             icon: 'none',
            //             title: '支付密码错误'
            //           })
            //         } else {
            //           _goPay()
            //         }
            //       })
            //     }
            //   }
            // })
            this.showPassword = true
          }
        } else {
          this._goPay()
        }


      },


      _goPay () {
        // 地址
        const address = this.addressList.filter(x => x.selected)
        // console.log(address)
        if (address.length === 0) {
          return uni.showToast({
            icon: 'none',
            title: '请选择收货地址'
          })
        }
        const address_id = (address && address[0] && address[0].id) || 0
        // android中提交, selected_sku_text 会变乱码
        if (this.params.selected_sku_text) {
          if (Array.isArray(this.params.selected_sku_text)) {
            this.params.selected_sku_text.forEach(x => {
              // 会是乱码
              // console.log(22, x)
            })
          }
        }
        // 购物车没有问题, 所以只需要处理单个商品下单
        if (!this.params.cart && this.params.product_id && this.productList[0] && this.productList[0].selected_sku_text) {
          const one = this.productList[0]
          // console.log(333, one.selected_sku_text)
          this.params.selected_sku_text = one.selected_sku_text
        }
        // console.log('param', this.params)
        orderModel.createOrder({
          ...this.params,
          address_id,
          remark: this.remark
        }).then(response => {

          let { data } = response
          data = base64.parse(data)

          console.log(data)

          if (+data.amount == 0) {

            uni.showToast({
              title: '下单成功',
            })
            this.params.ok = true
            this.$store.dispatch('Order/set_params', {}).then(() => {
              setTimeout(() => {

                // 拼团跳转
                let type = 2
                if (this.params.create_group || this.params.random_group || this.params.join_group) {
                  type = 5
                }

                uni.navigateTo({
                  url: `/sub_service/order/index?type=${type}`
                })
              }, 1000)
            })
          } else {
            // 立即支付
            let serial = {
              order_id: data.order_id
            }
            serial = JSON.stringify(serial)

            console.log(serial)

            // uni.navigateTo({
            //   url: '/sub_main/pay/index?serial=' + serial
            // })

            /*#ifdef APP-PLUS*/
            // App端特有的逻辑
            // uni.navigateTo({
            //   url: '/sub_main/pay/app?serial=' + serial
            // })
            // 使用小程序支付
            // uni.showToast({
            //   title: serial
            // })
            // return
            goApp('/sub_main/pay/mini?serial=' + serial + '&is_order=true')
            /*#endif*/

            /*#ifdef H5*/
            // 在浏览器端（H5）执行的逻辑
            uni.navigateTo({
              url: '/sub_main/pay/index?serial=' + serial
            })
            /*#endif*/

            /*#ifdef MP-WEIXIN*/
            // 微信小程序端执行的逻辑
            uni.navigateTo({
              url: '/sub_main/pay/mini?serial=' + serial
            })
            /*#endif*/

          }

        })
      }

    }
	}
</script>

<style lang="scss" scoped>
$button-height: 100rpx;
$bottom-height: 130rpx;
.wrapper {
  background: $background_color;
  padding-bottom: $bottom-height;
  .pay-btn {
    position: fixed;
    z-index: 100;
    width: 100%;
    bottom: 0;
    height: $button-height;
    line-height: $button-height;
    background: $main_color;
    text-align: center;
    color: white;
  }
  .products {
    padding: 20rpx 0;
    .item {
      margin: 0rpx 20rpx 20rpx 20rpx;
      padding: 20rpx;
      background: white;
      display: flex;
      border-radius: 10rpx;
      align-items: center;
      .image {
        width: 160rpx;
        image {
          width: 100rpx;
          height: 100rpx;
          display: block;
          margin: auto;
        }
      }
      .desc {
        flex: 1;
        font-size: 24rpx;
        view {
          line-height: 18px;
        }
        .title {
          font-weight: 700;
          overflow: hidden;
        }
        .total {
          color: red;
        }
      }
    }
  }
  .address, .calc, .account, .amount, .remark {
    margin: 20rpx;
    background: white;
    padding: 20rpx;
    font-size: 24rpx;
    border-radius: 10rpx;
    .title {
      font-weight: 700;
    }
    .item {
      display: flex;
      align-items: center;
      .text {
        width: 150rpx;
        text-align: right;
      }
      .num {
        color: red;
        font-weight: 700;
        padding-left: 20rpx;
      }
    }
  }
  .address {
    margin-top: -20rpx;
    //display: flex;
    .list {
      //background: red;
      .item {
        display: flex;
        margin-bottom: 10px;
        //line-height: 20px;
        //font-size: 24rpx;
        border-bottom: 1px solid #eee;
        padding: 10px 0;
        .selected {
          width: 55px;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .desc {
          flex: 1;
          text-align: left;
          padding-left: 10px;
          ::v-deep {
            .line {
              line-height: 20px;
              display: flex;
              .left {
                width: 90px;
                font-weight: 700;
              }
              .right {
                flex: 1;
                &.color {
                  color: red;
                }
                &.info {
                  word-break: break-word;
                }
              }
            }
          }
        }
      }
    }
    .ops {
      display: flex;
      justify-content: space-around;
      height: 30px;
    }
    .more {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .account {
  }
  .amount {
    .pay {
      text-indent: 100rpx;
      color: red;
      font-size: 34rpx;
      font-weight: 700;
    }
  }
  .remark {
    .title {
      margin-bottom: 10px;
    }
  }
}
</style>
